package com.witmore.neutron.ai.web.apiv2.login;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jk.common.response.ResponseResult;
import com.jk.common.utils.PasswordUtil;
import com.witmore.neutron.ai.db.entity.UserDO;
import com.witmore.neutron.ai.db.mapper.UserMapper;
import com.witmore.neutron.ai.web.annotation.NoLoginRequired;
import com.witmore.neutron.ai.web.controller.vo.LoginParam;
import com.witmore.neutron.ai.web.controller.vo.UserSession;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * V2 账号密码登录接口
 * Author: 豆子高
 * Date: 2025/5/15 15:03
 */
@RestController
@RequestMapping("/v2")
public class LoginControllerV2 {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    /**
     * 登录
     */
    @NoLoginRequired
    @ResponseBody
    @PostMapping("/login")
    public ResponseResult<UserSession> processLogin(@RequestBody LoginParam loginParam) {
        // 校验参数
        if (loginParam == null || !StringUtils.hasText(loginParam.getUsername()) || !StringUtils.hasText(loginParam.getPassword())) {
            return ResponseResult.fail(400, "用户名或密码不能为空");
        }
        UserDO userDO = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUserName, loginParam.getUsername())
        );
        if (userDO == null) {
            return ResponseResult.fail(401, "登录失败，用户不存在");
        }
        // 验证密码
        boolean checkedPassword = PasswordUtil.checkPassword(loginParam.getPassword(), userDO.getPassword());
        if (!checkedPassword) {
            return ResponseResult.fail(401, "登录失败，密码错误");
        }
        return ResponseResult.success(userService.setUserSession(userDO));
    }


    /**
     * 退出登录
     */
    @ResponseBody
    @RequestMapping("/logout")
    public ResponseResult<Void> logout() {
        GlobalAccountSession.removeUserInfo();
        return ResponseResult.success();
    }

}
